import 'dart:ffi' as ffi1;
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart' hide Image;
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_custom_cursor/cursor_manager.dart';
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:image/image.dart' as img2;

late Uint8List memoryCursorDataRawBGRA;
late Uint8List memoryCursorDataRawPNG;
late String cursorName;

late img2.Image img;

late String circlePoint;
late img2.Image circleImg;
late Uint8List circleDataRawPNG;
late Uint8List circleDataRawBGRA;

late String pencilPoint;
late img2.Image pencilImg;
late Uint8List pencilDataRawPNG;
late Uint8List pencilDataRawBGRA;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // read memory Cursor
  print("reading memory cursor");
  final byte = await rootBundle.load("assets/cursors/data.png");
  memoryCursorDataRawPNG = byte.buffer.asUint8List();
  img = await getImage(memoryCursorDataRawPNG);
  memoryCursorDataRawBGRA =
      (img.getBytes(format: img2.Format.bgra)).buffer.asUint8List();
  // register this cursor
  cursorName = await CursorManager.instance.registerCursor(CursorData()
    ..name = "test"
    ..buffer =
        Platform.isWindows ? memoryCursorDataRawBGRA : memoryCursorDataRawPNG
    ..height = img.height
    ..width = img.width
    ..hotX = 0
    ..hotY = 0);
  // test delete
  print("test delete");
  await CursorManager.instance.deleteCursor("test");
  cursorName = await CursorManager.instance.registerCursor(CursorData()
    ..name = "test"
    ..buffer =
        Platform.isWindows ? memoryCursorDataRawBGRA : memoryCursorDataRawPNG
    ..height = img.height
    ..width = img.width
    ..hotX = 0
    ..hotY = 0);

  final circleByte = await rootBundle.load("assets/cursors/circle.png");
  circleDataRawPNG = circleByte.buffer.asUint8List();
  circleImg = await getImage(circleDataRawPNG);
  circleDataRawBGRA =
      (circleImg.getBytes(format: img2.Format.bgra)).buffer.asUint8List();
  circlePoint = await CursorManager.instance.registerCursor(CursorData()
    ..name = "circlePoint"
    ..buffer = Platform.isWindows ? circleDataRawBGRA : circleDataRawPNG
    ..height = circleImg.height
    ..width = circleImg.width
    ..hotX = 0
    ..hotY = 0);

  final pencilByte = await rootBundle.load("assets/cursors/pencil.png");
  pencilDataRawPNG = pencilByte.buffer.asUint8List();
  pencilImg = await getImage(pencilDataRawPNG);
  pencilDataRawBGRA =
      (pencilImg.getBytes(format: img2.Format.bgra)).buffer.asUint8List();
  pencilPoint = await CursorManager.instance.registerCursor(CursorData()
    ..name = "pencilPoint"
    ..buffer = Platform.isWindows ? pencilDataRawBGRA : pencilDataRawPNG
    ..height = pencilImg.height
    ..width = pencilImg.width
    ..hotX = 0
    ..hotY = pencilImg.height.toDouble());

  runApp(const MyApp());
}

Future<img2.Image> getImage(Uint8List bytes) async {
  img = img2.decodePng(bytes)!;
  return img;
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String msg = "";

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    var style = const TextStyle(fontSize: 30);
    var styleSub = const TextStyle(fontSize: 16);
    print("rebuild");
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
            child: ListView(
              physics: const NeverScrollableScrollPhysics(),
          children: [
            MouseRegion(
              cursor: FlutterCustomMemoryImageCursor(key: cursorName),
              child: Row(
                children: [
                  // Image.memory(memoryCursorDataRawPNG),
                  Text("Memory Image Here", style: style),
                ],
              ),
            ),
            Text("OUTPUT: ${msg}"),
            // TextButton(
            //     onPressed: () async {
            //       msg =
            //           "${await FlutterCustomCursorController.instance.getCursorCacheKey()}";
            //       setState(() {});
            //     },
            //     child: Text("Last Cursor Cache List")),
            // TextButton(
            //     onPressed: () async {
            //       final keys = await FlutterCustomCursorController.instance
            //               .getCursorCacheKey() ??
            //           [];
            //       for (final key in keys) {
            //         await FlutterCustomCursorController.instance.freeCache(key);
            //       }
            //       msg =
            //           "${await FlutterCustomCursorController.instance.getCursorCacheKey()}";
            //       setState(() {});
            //     },
            //     child: Text("free all cache")),
            // TextButton(
            //     onPressed: () async {
            //       msg =
            //           "${await FlutterCustomCursorController.instance.lastCursorKey()}";
            //       setState(() {});
            //     },
            //     child: Text("Last Cursor Key"))
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10), // 垂直方向上的间距
              child: Container(color: Colors.grey, height: 2), // 自定义的分隔线
            ),
            Column(
              children: <Widget>[
                Text("圆圈", style: style),
                MouseRegion(
                    cursor: FlutterCustomMemoryImageCursor(key: circlePoint),
                    child: Container(
                      color: Colors.yellow,
                      width: 200,
                      height: 200,
                      child: DrawingBoard(),
                    )), // 使用 DrawingBoard 组件
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () async {
                        await CursorManager.instance.deleteCursor(circlePoint);
                      },
                      child: Text("删除指针", style: styleSub),
                    ),
                    TextButton(
                        onPressed: () async {
                          circlePoint = await CursorManager.instance.registerCursor(CursorData()
                            ..name = "circlePoint"
                            ..buffer = Platform.isWindows ? circleDataRawBGRA : circleDataRawPNG
                            ..height = circleImg.height
                            ..width = circleImg.width
                            ..hotX = 0
                            ..hotY = 0);
                        },
                        child: Text("初始化指针", style: styleSub))
                  ],
                ),
                Text("铅笔", style: style),
                MouseRegion(
                    cursor: FlutterCustomMemoryImageCursor(key: pencilPoint),
                    child: Container(
                      color: Colors.yellow,
                      width: 200,
                      height: 200,
                      child: DrawingBoard(),
                    )), // 使用 DrawingBoard 组件
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () async {
                        await CursorManager.instance.deleteCursor(pencilPoint);
                      },
                      child: Text("删除指针", style: styleSub),
                    ),
                    TextButton(
                        onPressed: () async {
                          pencilPoint = await CursorManager.instance.registerCursor(CursorData()
                            ..name = "pencilPoint"
                            ..buffer = Platform.isWindows ? pencilDataRawBGRA : pencilDataRawPNG
                            ..height = pencilImg.height
                            ..width = pencilImg.width
                            ..hotX = 0
                            ..hotY = pencilImg.height.toDouble());
                        },
                        child: Text("初始化指针", style: styleSub))
                  ],
                ),
              ],
            )
          ],
        )),
      ),
    );
  }
}

class DrawingBoard extends StatefulWidget {
  @override
  _DrawingBoardState createState() => _DrawingBoardState();
}

class _DrawingBoardState extends State<DrawingBoard> {
  List<Offset?> points = [];

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onPanUpdate: (details) {
          setState(() {
            points.add(details.localPosition);
          });
        },
        onPanEnd: (details) {
          points.add(null); // 添加一个空点，用于分隔线条
        },
        child: CustomPaint(
          painter: MyPainter(points),
          size: Size.infinite,
        ));
  }
}

class MyPainter extends CustomPainter {
  final List<Offset?> points;

  MyPainter(this.points);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5.0;

    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        if (points[i]!.dx! >= 0 &&
            points[i]!.dy! >= 0 &&
            points[i + 1]!.dx! >= 0 &&
            points[i + 1]!.dy! >= 0) {
          if (points[i]!.dx! <= size.width &&
              points[i]!.dy! <= size.height &&
              points[i + 1]!.dx! <= size.width &&
              points[i + 1]!.dy! <= size.height) {
            canvas.drawLine(points[i]!, points[i + 1]!, paint);
          }
        }
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
